<template>
	<view class="box">
		<view class="head">
			<view class="btnStyle add btn" @click="addFn">
				添加 </view> <el-pagination :current-page="1" :page-size="3" :page-sizes="sizes" small
				@size-change="getSize" @current-change="getPage" layout="total, sizes, prev, pager, next, jumper"
				:total="filterDatas.length " />
		</view>
		<el-table :data='tables' max-height="650">
			<el-table-column prop="id" v-if='false'></el-table-column>
			<el-table-column prop="name" label="运动名称" align="center"></el-table-column>
			<el-table-column label="运动图片" align="center">
				<template slot-scope="scope">
					<image :src="scope.row.src" mode="widthFix" style="width: 50px;"></image>
				</template>
			</el-table-column>
			<el-table-column prop="calorie" label="卡路里(每分)" align="center"></el-table-column>
			<el-table-column sortable :formatter="typeFormatter" prop="stype" label="运动类型"
				align="center"></el-table-column>
			<el-table-column label="操作" align="center" fixed="right">
				<template #header>
					<el-input @input="filterFn" v-model="search" size="small" placeholder="请输入运动名称" />
				</template>
				<template slot-scope="scope">
					<view class="btnStyle" style="margin-right: 15px;" @click="delDialogFn(scope.row.id ,scope.$index)">
						删除
					</view>
					<view class="btnStyle" @click="amend(scope.row )">修改
					</view>
				</template>
			</el-table-column>
		</el-table>
		<uni-popup ref="sport" background-color="#fff">
			<view class="popup-content">
				<view class="popup_head">{{activeId?'修改':'新增'}}</view>
				<uni-forms ref="formRef" labelWidth="100px" :modelValue="formData" label-align="center" :rules="rules">
					<uni-forms-item label="运动名称" required name="name">
						<uni-easyinput v-model.trim="formData.name" placeholder="请输入运动名称" maxlength="20" />
					</uni-forms-item>
					<uni-forms-item label="卡路里(每分)" required name="calorie">
						<uni-easyinput v-model.trim="formData.calorie" placeholder="请输入每分钟消耗的卡路里" maxlength="20" />
					</uni-forms-item>
					<uni-forms-item label="类型" required name="stype">
						<uni-data-checkbox v-model="formData.stype" :localdata="stypes" />
					</uni-forms-item>
					<view v-if="activeId&&!isAdmend" class="videos">
						<view class="amendVideo" @click="isAdmend=true;formData.src=[]">修改图片</view>
						<image :src="formData.src[0]" mode="widthFix" style="width: 100px;"></image>
					</view>
					<uni-forms-item label="上传图片" required name="src" v-else>
						<uni-file-picker limit="1" style="padding: 0 10px;" v-model="formData.src"
							file-mediatype="image"></uni-file-picker>
					</uni-forms-item>
				</uni-forms>
				<view class=" inner-center">
					<button size="mini" class="btn" @click="submit">{{activeId==''?'提交':'修改'}}</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		verify,
		addData,
		getSportData,
		remove
	} from '../database/index.js'

	export default {
		name: 'sport',
		data() {
			return {
				isAdmend: false,
				rules: {
					name: {
						rules: [{
							required: true,
							errorMessage: '运动名称不能为空'
						}]
					},
					stype: {
						rules: [{
							required: true,
							errorMessage: '运动类型不能为空'
						}]
					},
					calorie: {
						rules: [{
							required: true,
							errorMessage: '卡路里不能为空'
						}, {
							format: 'number',
							errorMessage: '卡路里必须为数字'
						}, {
							minimum: 1,
							errorMessage: '卡路里不能小于0'
						}]
					},
					src: {
						rules: [{
							required: true,
							errorMessage: '图片不能为空'
						}]
					}
				},
				formData: {
					name: '',
					src: [],
					stype: '',
					calorie: ''
				},
				stypes: [{
					text: '有氧运动',
					value: 0
				}, {
					text: '力量训练',
					value: 1
				}, {
					text: '柔韧性运动',
					value: 2
				}],
				activeId: '',
				curentIndex: '',
				search: '',
				datas: [],
				page: 1,
				size: 3,
				sizes: [3, 5, 8],
				filterDatas: [],
				tables: []
			}
		},

		methods: {
			typeFormatter(row) {
				return row.stype == 0 ? '有氧运动' : row.stype == 1 ? '力量训练' : '柔韧性运动'
			},
			async show() {
				this.datas = await getSportData()
				this.filterFn()
			},
			addFn() {
				getSportData()
				this.clear()
				this.activeId = ''
				this.$refs.sport.open()
			},
			async amend(data) {
				this.activeId = data.id
				this.formData.name = data.name
				this.formData.stype = parseInt(data.stype)
				this.formData.calorie = data.calorie
				this.formData.src = [data.src]
				this.$forceUpdate()
				this.$refs.sport.open()
			},
			async delDialogFn(id) {
				let self = this
				uni.showModal({
					title: '提示',
					content: '是否确定删除该运动项目？',
					success: async function(res) {
						if (res.confirm) {
							let isdel = await remove('sport', {
								_id: id
							})
							if (isdel) {
								await remove('sportCollect', {
									sport_Id: id
								})
								await remove('sportTrain', {
									train_id: id
								})
								self.datas = self.datas.filter(item => item.id !== id);
								self.filterFn()
								self.$showMsg('删除成功')
							} else {
								self.$showMsg('删除失败')
							}
						}
					}
				});
			},
			async clear() {
				this.formData = {
					name: '',
					src: [],
					type: '',
					calorie: ''
				}
				this.isAdmend = false
				this.show()
			},
			async upload() {
				if (this.activeId) {
					console.log(this.formData);
					this.$refs.sport.close()
					let [admend, msg] = await verify('sport', {
						_id: this.activeId
					}, {
						sport_src: this.formData.src[0].url ? this.formData.src[0].url : this.formData.src[0],
						sport_calorie: this.formData.calorie,
						sport_type: this.formData.stype,
						sport_name: this.formData.name
					})
					if (admend) {
						this.updateData(this.formData.src[0].url ? this.formData.src[0].url : this.formData.src[0])
						this.$showMsg('修改成功')
						this.filterFn()
						this.clear()
					} else {
						this.$showMsg('修改失败')
					}
				} else {
					this.$refs.sport.close()
					let [isadd, id, msg] = await addData('sport', {
						sport_src: this.formData.src[0].url,
						sport_calorie: this.formData.calorie,
						sport_type: this.formData.stype,
						sport_name: this.formData.name
					})
					console.log(111, id);
					if (isadd) {
						this.$showMsg('添加成功')
						this.datas.push({
							id: id,
							src: this.formData.src[0].url,
							name: this.formData.name,
							type: this.formData.stype,
							calorie: this.formData.calorie
						})
						this.filterFn()
						this.clear()
					} else {
						this.$showMsg('添加失败')
					}
				}

			},
			updateData(url) {
				for (let data of this.datas) {
					if (data.id == this.activeId) {
						data.src = url
						data.name = this.formData.name
						data.type = this.formData.stype
						data.calorie = this.formData.calorie
					}
				}
			},
			async submit() {
				let self = this
				this.$refs.formRef.validate().then(async res => {
					self.upload()
				}).catch(err => {
					console.log('err', err);
				})
			},

			getPage(val) {
				this.page = val
				this.filterFn(val, 2)
			},
			getSize(val) {
				this.size = val
				this.filterFn(val, 1)

			},
			filterFn(val, type) {
				let size = this.size
				let page = this.page
				if (type == 1) {
					size = val
				} else if (type == 2) {
					page = val
				}
				let table = this.datas.filter(
					(data) =>
					!this.search ||
					data.name.toLowerCase().includes(this.search.toLowerCase())
				)
				let start = page == 1 ? 0 : (page - 1) * size
				let end = size * page > table.length ? table.length : size * page
				this.filterDatas = table.slice(0)
				if (start >= end) {
					start = 0
				}
				this.tables = table.slice(start, end)
			}

		}
	}
</script>

<style lang="scss" scoped>
	::v-deep {
		uni-button[type=primary] {
			background-color: #4682B4;
		}
	}

	.videos {
		text-align: center;
		margin: 0 10px;
		margin-bottom: 20px;

		.amendVideo {
			text-align: right;
			margin-bottom: 10px;
		}
	}

	.btn {
		width: 100px;
		text-align: center;
		color: white;
		background-color: #4682B4;
	}

	::v-deep {
		.uni-popup__wrapper {
			width: 400px;
			border-radius: 10px;
			padding: 15px;
		}
	}

	::v-deep {
		.tip {
			.uni-popup__wrapper {
				width: 50px;
				border-radius: 10px;
				margin-top: 80px;
				margin-left: 500px;
			}
		}

	}

	.box {
		padding: 20px;
		color: black;

		uni-forms-item {
			margin-bottom: 20px;

			.uni-forms-item__content {
				width: 200px;
			}
		}

		.popup-content {
			padding: 10px 20px;

			.popup_head {
				padding-left: 30px;
				font-size: 25px;
				text-align: center;
				color: #4169E1;
				letter-spacing: 15px;
				margin-bottom: 10px;
			}
		}
	}

	.btnStyle {
		letter-spacing: 2px;
		color: white;
		background-color: #4682B4;
		width: 50px;
		text-align: center;
		border-radius: 5px;
		padding: 5px;
		display: inline-block;
	}

	.head {
		margin-bottom: 10px;
		display: flex;
		justify-content: space-between;
	}

	.add {
		padding: 5px 20px;

	}
</style>